import React, { useState, useEffect, useRef } from 'react';
import {
  Layout,
  Card,
  List,
  Avatar,
  Button,
  Input,
  Modal,
  Form,
  message,
  Space,
  Typography,
  Divider,
  Badge,
  Empty,
  Spin,
  Dropdown,
  Menu,
  Tooltip
} from 'antd';
import './ChatPage.css';
import {
  MessageOutlined,
  UserOutlined,
  SendOutlined,
  PlusOutlined,
  MoreOutlined,
  DeleteOutlined,
  UserAddOutlined,
  TeamOutlined,
  PaperClipOutlined,
  SmileOutlined
} from '@ant-design/icons';
import { chatService, friendsService } from '../services/api';

const { Title, Text } = Typography;
const { TextArea } = Input;

interface ChatRoom {
  id: number;
  name?: string;
  room_type: 'private' | 'group';
  description?: string;
  avatar?: string;
  created_at: string;
  updated_at: string;
  last_message?: string;
  last_message_time?: string;
  unread_count: number;
  is_online?: boolean; // 添加在线状态
}

interface ChatMessage {
  id: number;
  sender_id: number;
  message_type: 'text' | 'image' | 'file' | 'system';
  content: string;
  file_url?: string;
  file_name?: string;
  file_size?: number;
  reply_to?: number;
  created_at: string;
  sender_name: string;
  sender_avatar?: string;
  reply_content?: string;
  reply_sender_name?: string;
}

interface RoomMember {
  id: number;
  username: string;
  avatar?: string;
  is_online?: boolean;
  role: 'admin' | 'member';
  joined_at: string;
  last_read_at: string;
}

const Chat: React.FC = () => {
  const [rooms, setRooms] = useState<ChatRoom[]>([]);
  const [currentRoom, setCurrentRoom] = useState<ChatRoom | null>(null);
  const [messages, setMessages] = useState<ChatMessage[]>([]);
  const [members, setMembers] = useState<RoomMember[]>([]);
  const [loading, setLoading] = useState(true);
  const [messageLoading, setMessageLoading] = useState(false);
  const [newMessage, setNewMessage] = useState('');
  const [createGroupVisible, setCreateGroupVisible] = useState(false);
  const [createPrivateVisible, setCreatePrivateVisible] = useState(false);
  const [addMemberVisible, setAddMemberVisible] = useState(false);
  const [friends, setFriends] = useState<any[]>([]);
  const [selectedFriends, setSelectedFriends] = useState<number[]>([]);
  const [showEmojiPicker, setShowEmojiPicker] = useState(false);
  const [deleteModalVisible, setDeleteModalVisible] = useState(false);
  const [selectedFile, setSelectedFile] = useState<File | null>(null);
  const [form] = Form.useForm();
  const messagesEndRef = useRef<HTMLDivElement>(null);

  // 页面初始化
  useEffect(() => {
    loadRooms();
    loadFriends();
  }, []);

  // 当rooms加载完成后，恢复选择的聊天室
  useEffect(() => {
    if (rooms.length > 0 && !currentRoom) {
      const savedRoomId = localStorage.getItem('selectedChatRoom');
      if (savedRoomId) {
        const savedRoom = rooms.find(room => room.id === parseInt(savedRoomId));
        if (savedRoom) {
          setCurrentRoom(savedRoom);
          loadMessages(savedRoom.id);
          loadMembers(savedRoom.id);
        }
      }
    }
  }, [rooms, currentRoom]);


  // 滚动到底部
  useEffect(() => {
    scrollToBottom();
  }, [messages]);

  // 点击外部关闭表情包选择器
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      const target = event.target as HTMLElement;
      if (showEmojiPicker && !target.closest('.emoji-picker') && !target.closest('[title="表情包"]')) {
        setShowEmojiPicker(false);
      }
    };

    if (showEmojiPicker) {
      document.addEventListener('mousedown', handleClickOutside);
    }

    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, [showEmojiPicker]);

  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  };

  // 加载聊天室列表
  const loadRooms = async () => {
    try {
      setLoading(true);
      const response = await chatService.getRooms();
      if (response && (response as any).success) {
        setRooms((response as any).rooms || []);
        // 移除自动选择第一个聊天室的逻辑
        // 让用户手动选择或显示引导页面
      }
    } catch (error: any) {
      console.error('加载聊天室失败:', error);
      message.error('加载聊天室失败');
    } finally {
      setLoading(false);
    }
  };

  // 加载好友列表
  const loadFriends = async () => {
    try {
      const response = await friendsService.getFriends();
      if (response && (response as any).success) {
        setFriends((response as any).friends || []);
      }
    } catch (error: any) {
      console.error('加载好友列表失败:', error);
    }
  };

  // 加载聊天消息
  const loadMessages = async (roomId: number) => {
    try {
      setMessageLoading(true);
      const response = await chatService.getMessages(roomId);
      if (response && (response as any).success) {
        setMessages((response as any).messages || []);
      }
    } catch (error: any) {
      console.error('加载消息失败:', error);
      message.error('加载消息失败');
    } finally {
      setMessageLoading(false);
    }
  };

  // 加载聊天室成员
  const loadMembers = async (roomId: number) => {
    try {
      const response = await chatService.getRoomMembers(roomId);
      if (response && (response as any).success) {
        setMembers((response as any).members || []);
      }
    } catch (error: any) {
      console.error('加载成员失败:', error);
    }
  };

  // 选择聊天室
  const handleSelectRoom = (room: ChatRoom) => {
    setCurrentRoom(room);
    loadMessages(room.id);
    loadMembers(room.id);
    
    // 保存选择的聊天室到localStorage
    localStorage.setItem('selectedChatRoom', room.id.toString());
  };

  // 发送消息
  const handleSendMessage = async () => {
    if ((!newMessage.trim() && !selectedFile) || !currentRoom) return;

    const messageText = newMessage.trim();
    const fileToSend = selectedFile;

    // 立即清空输入框和文件选择，避免加载状态
    setNewMessage('');
    setSelectedFile(null);
    setShowEmojiPicker(false);

    // 乐观更新：立即添加消息到界面
    const tempMessage: ChatMessage = {
      id: Date.now(), // 临时ID
      sender_id: 1, // 假设当前用户ID为1
      message_type: fileToSend ? 'file' : 'text',
      content: messageText || (fileToSend ? `发送了文件: ${fileToSend.name}` : ''),
      file_name: fileToSend?.name,
      file_size: fileToSend?.size,
      file_url: fileToSend ? `/uploads/chat/temp-${Date.now()}` : undefined, // 临时URL
      created_at: new Date().toISOString(),
      sender_name: '我',
      sender_avatar: undefined
    };

    // 立即显示消息
    setMessages(prev => [...prev, tempMessage]);

    try {
      let response: any;
      
      if (fileToSend) {
        // 发送文件
        const formData = new FormData();
        formData.append('file', fileToSend);
        formData.append('message', messageText || `发送了文件: ${fileToSend.name}`);
        
        response = await chatService.sendFile(currentRoom.id, formData);
      } else {
        // 发送文本消息
        response = await chatService.sendMessage(
          currentRoom.id,
          messageText
        );
      }
      
      if (response && (response as any).success) {
        // 发送成功后，更新聊天室列表中的最后消息
        setRooms(prevRooms => 
          prevRooms.map(room => 
            room.id === currentRoom.id 
              ? {
                  ...room,
                  last_message: messageText || (fileToSend ? `发送了文件: ${fileToSend.name}` : ''),
                  last_message_time: new Date().toISOString()
                }
              : room
          )
        );
        
        // 文件消息发送成功后，更新临时消息为真实消息
        if (fileToSend && response && (response as any).file_url) {
          setMessages(prev => 
            prev.map(msg => 
              msg.id === tempMessage.id 
                ? {
                    ...msg,
                    id: (response as any).message_id,
                    file_url: (response as any).file_url
                  }
                : msg
            )
          );
        }
      }
    } catch (error: any) {
      console.error('发送消息失败:', error);
      message.error('发送消息失败');
      // 如果发送失败，移除临时消息并恢复输入内容
      setMessages(prev => prev.filter(msg => msg.id !== tempMessage.id));
      setNewMessage(messageText);
      if (fileToSend) {
        setSelectedFile(fileToSend);
      }
    }
  };

  // 创建群聊
  const handleCreateGroup = async (values: any) => {
    try {
      const response = await chatService.createGroupChat(
        values.name,
        values.description,
        selectedFriends
      );
      if (response && (response as any).success) {
        message.success('群聊创建成功');
        setCreateGroupVisible(false);
        setSelectedFriends([]);
        form.resetFields();
        // 创建成功后自动进入聊天
        const roomId = (response as any).room_id;
        if (roomId) {
          // 先设置当前聊天室，然后重新加载房间列表
          const tempRoom = {
            id: roomId,
            name: values.name || '新群聊',
            room_type: 'group' as const,
            created_at: new Date().toISOString(),
            updated_at: new Date().toISOString(),
            unread_count: 0,
            last_message: '',
            last_message_time: undefined,
            is_online: false
          };
          setCurrentRoom(tempRoom);
          localStorage.setItem('selectedChatRoom', roomId.toString());
          loadRooms();
        }
      }
    } catch (error: any) {
      console.error('创建群聊失败:', error);
      message.error('创建群聊失败');
    }
  };

  // 创建私聊
  const handleCreatePrivate = async (values: any) => {
    try {
      const response = await chatService.createPrivateChat(selectedFriends[0]);
      if (response && (response as any).success) {
        message.success('私聊创建成功');
        setCreatePrivateVisible(false);
        setSelectedFriends([]);
        // 创建成功后自动进入聊天
        const roomId = (response as any).room_id;
        if (roomId) {
          // 先设置当前聊天室，然后重新加载房间列表
          // 获取选中好友的信息
          const selectedFriend = friends.find(friend => friend.id === selectedFriends[0]);
          const tempRoom = {
            id: roomId,
            name: selectedFriend?.username || '私聊',
            room_type: 'private' as const,
            created_at: new Date().toISOString(),
            updated_at: new Date().toISOString(),
            unread_count: 0,
            last_message: '',
            last_message_time: undefined,
            is_online: false
          };
          setCurrentRoom(tempRoom);
          localStorage.setItem('selectedChatRoom', roomId.toString());
          loadRooms();
        }
      }
    } catch (error: any) {
      console.error('创建私聊失败:', error);
      message.error('创建私聊失败');
    }
  };

  // 添加群聊成员
  const handleAddMembers = async () => {
    if (!currentRoom || selectedFriends.length === 0) return;

    try {
      const response = await chatService.addRoomMembers(
        currentRoom.id,
        selectedFriends
      );
      if (response && (response as any).success) {
        message.success('成员添加成功');
        setAddMemberVisible(false);
        setSelectedFriends([]);
        loadMembers(currentRoom.id);
      }
    } catch (error: any) {
      console.error('添加成员失败:', error);
      message.error('添加成员失败');
    }
  };

  // 删除聊天
  const handleDeleteChat = async (roomId: number) => {
    try {
      console.log('开始删除聊天室:', roomId);
      const response = await chatService.deleteRoom(roomId);
      console.log('删除响应:', response);
      if (response && (response as any).success) {
        message.success('聊天已删除');
        setCurrentRoom(null);
        localStorage.removeItem('selectedChatRoom');
        loadRooms();
      } else {
        message.error('删除失败');
      }
    } catch (error: any) {
      console.error('删除聊天失败:', error);
      message.error('删除聊天失败: ' + (error.message || '未知错误'));
    }
  };

  // 获取聊天室显示名称
  const getRoomDisplayName = (room: ChatRoom) => {
    if (room.room_type === 'private') {
      // 对于私聊，优先使用room.name，如果没有则显示"私聊"
      return room.name || '私聊';
    }
    return room.name || '群聊';
  };

  // 获取消息时间显示
  const getMessageTime = (createdAt: string) => {
    const date = new Date(createdAt);
    const now = new Date();
    const diff = now.getTime() - date.getTime();
    
    if (diff < 60000) { // 1分钟内
      return '刚刚';
    } else if (diff < 3600000) { // 1小时内
      return `${Math.floor(diff / 60000)}分钟前`;
    } else if (diff < 86400000) { // 1天内
      return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
    } else {
      return date.toLocaleDateString('zh-CN');
    }
  };

  return (
    <div className="chat-page-container" style={{ 
      background: 'transparent',
      height: 'calc(100vh - 40px)', // 减去Layout的padding
      overflow: 'hidden'
    }}>
      <div style={{ display: 'flex', height: '100%' }}>
        {/* 左侧聊天室列表 */}
        <div style={{ 
          width: '300px', 
          borderRight: '1px solid #f0f0f0',
          display: 'flex',
          flexDirection: 'column'
        }}>
          {/* 头部 */}
          <div style={{ 
            padding: '16px', 
            borderBottom: '1px solid #f0f0f0',
            display: 'flex',
            justifyContent: 'space-between',
            alignItems: 'center'
          }}>
            <Title level={4} style={{ margin: 0 }}>
              <MessageOutlined style={{ marginRight: '8px' }} />
              聊天
            </Title>
            <Space>
              <Button
                icon={<UserOutlined />}
                onClick={() => setCreatePrivateVisible(true)}
              >
                私聊
              </Button>
              <Button
                type="primary"
                icon={<PlusOutlined />}
                onClick={() => setCreateGroupVisible(true)}
              >
                群聊
              </Button>
            </Space>
          </div>

          {/* 聊天室列表 */}
          <div style={{ flex: 1, overflowY: 'auto' }}>
            {loading ? (
              <div style={{ textAlign: 'center', padding: '40px' }}>
                <Spin />
              </div>
            ) : rooms.length === 0 ? (
              <Empty
                image={Empty.PRESENTED_IMAGE_SIMPLE}
                description="暂无聊天记录"
                style={{ marginTop: '40px' }}
              />
            ) : (
              <List
                dataSource={rooms}
                renderItem={(room) => (
                  <List.Item
                    style={{
                      cursor: 'pointer',
                      backgroundColor: currentRoom?.id === room.id ? '#f0f8ff' : 'transparent',
                      padding: '12px 16px'
                    }}
                    onClick={() => handleSelectRoom(room)}
                  >
                    <List.Item.Meta
                      avatar={
                        <Badge count={room.unread_count} size="small">
                          <Avatar 
                            src={room.avatar} 
                            icon={room.room_type === 'private' ? <UserOutlined /> : <TeamOutlined />}
                            size="large"
                          />
                        </Badge>
                      }
                      title={
                        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                          <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                            <span>{getRoomDisplayName(room)}</span>
                            {room.room_type === 'private' && (
                              <Badge 
                                status={room.is_online ? 'success' : 'default'} 
                                text={room.is_online ? '在线' : '离线'}
                                style={{ fontSize: '10px' }}
                              />
                            )}
                          </div>
                          {room.last_message_time && (
                            <Text style={{ fontSize: '12px', color: '#999' }}>
                              {getMessageTime(room.last_message_time)}
                            </Text>
                          )}
                        </div>
                      }
                      description={
                        <div>
                          <div style={{ 
                            overflow: 'hidden',
                            textOverflow: 'ellipsis',
                            whiteSpace: 'nowrap',
                            maxWidth: '200px'
                          }}>
                            {room.last_message || '暂无消息'}
                          </div>
                        </div>
                      }
                    />
                  </List.Item>
                )}
              />
            )}
          </div>
        </div>

        {/* 右侧聊天区域 */}
        <div style={{ flex: 1, display: 'flex', flexDirection: 'column' }}>
          {currentRoom && !loading ? (
            <>
              {/* 聊天室头部 */}
              <div style={{ 
                padding: '16px', 
                borderBottom: '1px solid #f0f0f0',
                display: 'flex',
                justifyContent: 'space-between',
                alignItems: 'center'
              }}>
                <div style={{ display: 'flex', alignItems: 'center' }}>
                  <Avatar 
                    src={currentRoom.avatar} 
                    icon={currentRoom.room_type === 'private' ? <UserOutlined /> : <TeamOutlined />}
                    size="large"
                    style={{ marginRight: '12px' }}
                  />
                  <div>
                    <Title level={4} style={{ margin: 0 }}>
                      {getRoomDisplayName(currentRoom)}
                      {currentRoom.is_online && (
                        <Badge status="success" text="在线" style={{ marginLeft: '8px' }} />
                      )}
                    </Title>
                    <Text style={{ color: '#666' }}>
                      {currentRoom.room_type === 'group' ? `${members.length} 名成员` : '私聊'}
                    </Text>
                  </div>
                </div>
                <Space>
                  {currentRoom.room_type === 'group' && (
                    <Button
                      icon={<UserAddOutlined />}
                      onClick={() => setAddMemberVisible(true)}
                    >
                      添加成员
                    </Button>
                  )}
                  <Button
                    danger
                    icon={<DeleteOutlined />}
                    onClick={() => {
                      console.log('删除按钮被点击', currentRoom);
                      setDeleteModalVisible(true);
                    }}
                  >
                    删除聊天
                  </Button>
                </Space>
              </div>

              {/* 消息列表 */}
              <div style={{ 
                flex: 1, 
                overflowY: 'auto', 
                padding: '16px',
                background: '#fafafa'
              }}>
                {messageLoading ? (
                  <div style={{ textAlign: 'center', padding: '40px' }}>
                    <Spin />
                  </div>
                ) : messages.length === 0 ? (
                  <Empty
                    image={Empty.PRESENTED_IMAGE_SIMPLE}
                    description="暂无消息，开始聊天吧！"
                    style={{ marginTop: '40px' }}
                  />
                ) : (
                  <div>
                    {messages.map((msg) => (
                      <div
                        key={msg.id}
                        style={{
                          marginBottom: '16px',
                          display: 'flex',
                          flexDirection: msg.sender_id === 1 ? 'row-reverse' : 'row' // 假设当前用户ID为1
                        }}
                      >
                        <Avatar 
                          src={msg.sender_avatar} 
                          icon={<UserOutlined />}
                          size="small"
                          style={{ margin: msg.sender_id === 1 ? '0 0 0 8px' : '0 8px 0 0' }}
                        />
                        <div style={{ maxWidth: '70%' }}>
                          <div
                            style={{
                              background: msg.sender_id === 1 ? '#1890ff' : '#fff',
                              color: msg.sender_id === 1 ? '#fff' : '#333',
                              padding: '8px 12px',
                              borderRadius: '12px',
                              boxShadow: '0 1px 2px rgba(0,0,0,0.1)'
                            }}
                          >
                            {msg.message_type === 'file' ? (
                              <div>
                                <div style={{ 
                                  display: 'flex', 
                                  alignItems: 'center', 
                                  gap: '8px',
                                  marginBottom: '4px'
                                }}>
                                  <span style={{ fontSize: '16px' }}>📎</span>
                                  <span style={{ fontWeight: 'bold' }}>{msg.file_name || '未知文件'}</span>
                                </div>
                                <div style={{ 
                                  fontSize: '12px', 
                                  opacity: 0.8,
                                  marginBottom: '4px'
                                }}>
                                  {msg.file_size ? `${(msg.file_size / 1024).toFixed(1)} KB` : '未知大小'}
                                </div>
                                <Button
                                  type="link"
                                  size="small"
                                  onClick={async () => {
                                    // 下载文件
                                    if (msg.file_url && msg.file_name) {
                                      // 检查是否是临时消息（没有真实文件URL）
                                      if (msg.file_url.includes('temp-')) {
                                        message.info('文件正在上传中，请稍后再试');
                                        return;
                                      }
                                      
                                      try {
                                        const filename = msg.file_url.split('/').pop();
                                        const token = localStorage.getItem('token');
                                        
                                        // 使用fetch下载文件
                                        const response = await fetch(`http://localhost:3002/api/chat/files/${filename}`, {
                                          headers: {
                                            'Authorization': `Bearer ${token}`
                                          }
                                        });
                                        
                                        if (response.ok) {
                                          const blob = await response.blob();
                                          const url = window.URL.createObjectURL(blob);
                                          const link = document.createElement('a');
                                          link.href = url;
                                          link.download = msg.file_name;
                                          document.body.appendChild(link);
                                          link.click();
                                          document.body.removeChild(link);
                                          window.URL.revokeObjectURL(url);
                                        } else {
                                          message.error('下载失败');
                                        }
                                      } catch (error) {
                                        console.error('下载文件失败:', error);
                                        message.error('下载文件失败');
                                      }
                                    }
                                  }}
                                  style={{ 
                                    color: msg.sender_id === 1 ? '#fff' : '#1890ff',
                                    padding: 0,
                                    height: 'auto'
                                  }}
                                >
                                  {msg.file_url && msg.file_url.includes('temp-') ? '上传中...' : '下载文件'}
                                </Button>
                              </div>
                            ) : (
                              <div>{msg.content}</div>
                            )}
                            <div style={{ 
                              fontSize: '11px', 
                              opacity: 0.7,
                              marginTop: '4px'
                            }}>
                              {getMessageTime(msg.created_at)}
                            </div>
                          </div>
                        </div>
                      </div>
                    ))}
                    <div ref={messagesEndRef} />
                  </div>
                )}
              </div>

              {/* 消息输入框 */}
              <div style={{ 
                padding: '16px', 
                borderTop: '1px solid #f0f0f0',
                background: '#fff',
                position: 'relative'
              }}>
                {/* 文件选择显示 */}
                {selectedFile && (
                  <div style={{ 
                    marginBottom: '8px', 
                    padding: '8px', 
                    background: '#f5f5f5', 
                    borderRadius: '4px',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'space-between'
                  }}>
                    <Text>📎 {selectedFile.name}</Text>
                    <Button 
                      size="small" 
                      onClick={() => setSelectedFile(null)}
                    >
                      取消
                    </Button>
                  </div>
                )}
                
                <div style={{ display: 'flex', gap: '8px' }}>
                  <div style={{ display: 'flex', gap: '4px' }}>
                    <Button
                      icon={<PaperClipOutlined />}
                      onClick={() => document.getElementById('fileInput')?.click()}
                      title="发送文件"
                    />
                    <Button
                      icon={<SmileOutlined />}
                      onClick={() => setShowEmojiPicker(!showEmojiPicker)}
                      title="表情包"
                    />
                  </div>
                  
                  <TextArea
                    value={newMessage}
                    onChange={(e) => setNewMessage(e.target.value)}
                    placeholder="输入消息..."
                    autoSize={{ minRows: 1, maxRows: 4 }}
                    onPressEnter={(e) => {
                      if (!e.shiftKey) {
                        e.preventDefault();
                        handleSendMessage();
                      }
                    }}
                    style={{ flex: 1 }}
                  />
                  
                  <Button
                    type="primary"
                    icon={<SendOutlined />}
                    onClick={handleSendMessage}
                    disabled={!newMessage.trim() && !selectedFile}
                  >
                    发送
                  </Button>
                </div>
                
                {/* 隐藏的文件输入 */}
                <input
                  id="fileInput"
                  type="file"
                  style={{ display: 'none' }}
                  onChange={(e) => {
                    const file = e.target.files?.[0];
                    if (file) {
                      setSelectedFile(file);
                    }
                    // 清空input值，允许重复选择同一文件
                    e.target.value = '';
                  }}
                />
                
                {/* 表情包选择器 */}
                {showEmojiPicker && (
                  <div className="emoji-picker" style={{
                    position: 'absolute',
                    bottom: '60px',
                    left: '8px',
                    background: '#fff',
                    border: '1px solid #d9d9d9',
                    borderRadius: '12px',
                    padding: '12px',
                    boxShadow: '0 4px 12px rgba(0,0,0,0.15)',
                    zIndex: 1000,
                    maxHeight: '150px',
                    width: '240px',
                    overflowY: 'auto'
                  }}>
                    <div style={{ 
                      display: 'grid', 
                      gridTemplateColumns: 'repeat(8, 1fr)', 
                      gap: '4px',
                      textAlign: 'center'
                    }}>
                      {['😀', '😃', '😄', '😁', '😆', '😅', '😂', '🤣', '😊', '😇', '🙂', '🙃', '😉', '😌', '😍', '🥰', '😘', '😗', '😙', '😚', '😋', '😛', '😝', '😜', '🤪', '🤨', '🧐', '🤓', '😎', '🤩', '🥳', '😏', '😒', '😞', '😔', '😟', '😕', '🙁', '☹️', '😣', '😖', '😫', '😩', '🥺', '😢', '😭', '😤', '😠', '😡', '🤬', '🤯', '😳', '🥵', '🥶', '😱', '😨', '😰', '😥', '😓'].map(emoji => (
                        <div
                          key={emoji}
                          onClick={() => {
                            setNewMessage(prev => prev + emoji);
                            setShowEmojiPicker(false);
                          }}
                          style={{ 
                            cursor: 'pointer',
                            padding: '4px',
                            borderRadius: '4px',
                            fontSize: '16px',
                            transition: 'background-color 0.2s'
                          }}
                          onMouseEnter={(e) => {
                            e.currentTarget.style.backgroundColor = '#f5f5f5';
                          }}
                          onMouseLeave={(e) => {
                            e.currentTarget.style.backgroundColor = 'transparent';
                          }}
                        >
                          {emoji}
                        </div>
                      ))}
                    </div>
                  </div>
                )}
              </div>
            </>
          ) : (
            <div style={{ 
              flex: 1, 
              display: 'flex', 
              alignItems: 'center', 
              justifyContent: 'center',
              background: '#fafafa',
              flexDirection: 'column'
            }}>
              <div style={{ textAlign: 'center', padding: '40px' }}>
                <MessageOutlined style={{ fontSize: '64px', color: '#d9d9d9', marginBottom: '16px' }} />
                <Title level={3} style={{ color: '#666', marginBottom: '8px' }}>
                  开始聊天
                </Title>
                <Text style={{ color: '#999', fontSize: '16px' }}>
                  从左侧选择一个聊天室开始对话
                </Text>
                <div style={{ marginTop: '24px', display: 'flex', gap: '12px', justifyContent: 'center' }}>
                  <Button 
                    type="primary" 
                    icon={<PlusOutlined />}
                    onClick={() => setCreateGroupVisible(true)}
                    size="large"
                  >
                    创建群聊
                  </Button>
                  <Button 
                    type="default" 
                    icon={<UserOutlined />}
                    onClick={() => setCreatePrivateVisible(true)}
                    size="large"
                  >
                    创建私聊
                  </Button>
                </div>
              </div>
            </div>
          )}
        </div>
      </div>

      {/* 创建群聊模态框 */}
      <Modal
        title="创建群聊"
        open={createGroupVisible}
        onCancel={() => {
          setCreateGroupVisible(false);
          setSelectedFriends([]);
          form.resetFields();
        }}
        onOk={() => form.submit()}
        width={500}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleCreateGroup}
        >
          <Form.Item
            name="name"
            label="群聊名称"
            rules={[{ required: true, message: '请输入群聊名称' }]}
          >
            <Input placeholder="请输入群聊名称" />
          </Form.Item>
          <Form.Item
            name="description"
            label="群聊描述"
          >
            <Input.TextArea placeholder="请输入群聊描述" />
          </Form.Item>
          <Form.Item label="选择成员">
            <div style={{ maxHeight: '200px', overflowY: 'auto' }}>
              {friends.map(friend => (
                <div key={friend.id} style={{ marginBottom: '8px' }}>
                  <label style={{ display: 'flex', alignItems: 'center', cursor: 'pointer' }}>
                    <input
                      type="checkbox"
                      checked={selectedFriends.includes(friend.id)}
                      onChange={(e) => {
                        if (e.target.checked) {
                          setSelectedFriends([...selectedFriends, friend.id]);
                        } else {
                          setSelectedFriends(selectedFriends.filter(id => id !== friend.id));
                        }
                      }}
                      style={{ marginRight: '8px' }}
                    />
                    <Avatar 
                      src={friend.avatar} 
                      icon={<UserOutlined />}
                      size="small"
                      style={{ marginRight: '8px' }}
                    />
                    <span>{friend.username}</span>
                  </label>
                </div>
              ))}
            </div>
          </Form.Item>
        </Form>
      </Modal>

      {/* 添加成员模态框 */}
      <Modal
        title="添加成员"
        open={addMemberVisible}
        onCancel={() => {
          setAddMemberVisible(false);
          setSelectedFriends([]);
        }}
        onOk={handleAddMembers}
        width={400}
      >
        <div style={{ maxHeight: '300px', overflowY: 'auto' }}>
          {friends.map(friend => (
            <div key={friend.id} style={{ marginBottom: '8px' }}>
              <label style={{ display: 'flex', alignItems: 'center', cursor: 'pointer' }}>
                <input
                  type="checkbox"
                  checked={selectedFriends.includes(friend.id)}
                  onChange={(e) => {
                    if (e.target.checked) {
                      setSelectedFriends([...selectedFriends, friend.id]);
                    } else {
                      setSelectedFriends(selectedFriends.filter(id => id !== friend.id));
                    }
                  }}
                  style={{ marginRight: '8px' }}
                />
                <Avatar 
                  src={friend.avatar} 
                  icon={<UserOutlined />}
                  size="small"
                  style={{ marginRight: '8px' }}
                />
                <span>{friend.username}</span>
              </label>
            </div>
          ))}
        </div>
      </Modal>

      {/* 创建私聊模态框 */}
      <Modal
        title="创建私聊"
        open={createPrivateVisible}
        onCancel={() => {
          setCreatePrivateVisible(false);
          setSelectedFriends([]);
        }}
        onOk={() => {
          if (selectedFriends.length === 0) {
            message.warning('请选择一个好友');
            return;
          }
          handleCreatePrivate({});
        }}
        width={400}
      >
        <div style={{ marginBottom: '16px' }}>
          <Text>选择要私聊的好友：</Text>
        </div>
        <div style={{ maxHeight: '300px', overflowY: 'auto' }}>
          {friends.map(friend => (
            <div key={friend.id} style={{ marginBottom: '8px' }}>
              <label style={{ display: 'flex', alignItems: 'center', cursor: 'pointer' }}>
                <input
                  type="radio"
                  name="selectedFriend"
                  checked={selectedFriends.includes(friend.id)}
                  onChange={(e) => {
                    if (e.target.checked) {
                      setSelectedFriends([friend.id]);
                    }
                  }}
                  style={{ marginRight: '8px' }}
                />
                <Avatar 
                  src={friend.avatar} 
                  icon={<UserOutlined />}
                  size="small"
                  style={{ marginRight: '8px' }}
                />
                <span>{friend.username}</span>
              </label>
            </div>
          ))}
        </div>
      </Modal>

      {/* 删除确认Modal */}
      <Modal
        title="确认删除"
        open={deleteModalVisible}
        onOk={() => {
          console.log('确认删除', currentRoom?.id);
          if (currentRoom) {
            handleDeleteChat(currentRoom.id);
          }
          setDeleteModalVisible(false);
        }}
        onCancel={() => setDeleteModalVisible(false)}
        okText="删除"
        cancelText="取消"
        okType="danger"
        centered
      >
        <p>确定要删除与{currentRoom ? getRoomDisplayName(currentRoom) : ''}的聊天吗？</p>
        <p style={{ color: '#999', fontSize: '14px' }}>删除后无法恢复</p>
      </Modal>
    </div>
  );
};

export default Chat;